package org.shop.controller;

import org.shop.util.FileUploadUtil;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * 编写 Servlet，实现修改头像
 */
@WebServlet("/head.do")
@MultipartConfig
public class HeadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 第一：实例化 Part 对象 - 通过 file 表单控件中，name 属性实例化
        Part part = req.getPart("head");
        String userId = req.getParameter("user_id");
        String realPath = req.getServletContext().getRealPath("/images/");
        FileUploadUtil fileUploadUtil = new FileUploadUtil(1*1024*1024,"jpg,jpeg,png,webb,gif");
        String filename = fileUploadUtil.upload(part, realPath);
        // DAO 操作 ....
        System.out.println("用户：" + userId + "修改了头像为：" + filename);

        // 重定向或转发 ...
    }
}
